<template>
  <div class="myOrder">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="所有订单" name="first" />
      <el-tab-pane label="待付款" name="second" />
      <el-tab-pane label="待发货" name="third" />
      <el-tab-pane label="待收货" name="fourth" />
      <el-tab-pane label="待评价" name="fifth" />
      <el-tab-pane label="待成团" name="sixth" />
    </el-tabs>
    <div class="search">
      <el-input placeholder="商品名称/订单号" v-model="query.keyword" maxlength="20" class="input-with-select" />
      <svg-icon class="searchIcon" name="search" @click="searchOrder" />
    </div>
    <div class="sub-main" v-loading="listLoading">
      <OrderList
        :orderList="orderList"
        :page="page"
        @is-cancel="isCancel"
        @is-delete="isDelete"
        @is-confirm="isConfirm"
        @is-refund="isRefund"
        @handle-current-change="handleCurrentChange"
      />
    </div>
    <!-- 取消 -->
    <el-dialog
      v-model="visible.orderCancel"
      close-on-click-modal
      :before-close="handleClose"
      width="500"
      title="是否取消该订单"
      center
    >
      <div>
        <p>您确定要取消该订单吗？取消订单后，不能恢复。</p>
      </div>
      <template #footer>
        <el-button
          class="leftBtn"
          @click="handleClose"
        >取消</el-button>
        <el-button
          class="rightBtn"
          @click="handleOrderCancel"
        >确定</el-button>
      </template>
    </el-dialog>
    <!-- 删除 -->
    <el-dialog
      v-model="visible.orderDelete"
      close-on-click-modal
      :before-close="handleClose"
      width="500px"
      title="是否删除该订单"
      center
    >
      <p style="text-align: center;">您确定要删除该订单吗？删除订单后，不能恢复。</p>
      <template #footer>
        <el-button class="leftBtn" @click="handleClose">取消</el-button>
        <el-button class="rightBtn" @click="handleOrderDelete">确定</el-button>
      </template>
    </el-dialog>
    <!-- 收货 -->
    <el-dialog
      v-model="visible.orderConfirm" close-on-click-modal
      :before-close="handleClose"
      width="500px" title="是否确认收货" center>
      <p style="text-align: center;">为了保证您的售后权益，请收到商品检查无误后再确认收货</p>
      <template #footer>
        <el-button class="leftBtn" @click="handleClose">取消</el-button>
        <el-button class="rightBtn" @click="handleOrderConfirm">确定</el-button>
      </template>
    </el-dialog>
    <!-- 选择售后 -->
    <el-dialog
      class="refund"
      v-model="visible.orderRefund"
      width="50%"
      :before-close="handleClose"
      title="请选择售后商品"
      center
    >
      <div>
        <div class="mar-bot-20 fs18">
          <el-checkbox
            v-model="checked"
            @change="changeBox"
          >全选</el-checkbox>
        </div>
        <div class="box">
          <div
            class="mar-bot-10 fs14 font-color-999"
          >
            <span
              v-for="(val, inx) in item.values"
              :key="inx"
            >{{ val }}</span>
          </div>
          <p
            class="mar-bot-20 fs14 font-color-999"
          >x{{ item.number }}</p>
          <p
            style="color: #C83732;"
          >¥{{ item.price }}</p>
          <svg-icon
            class="choice"
            name="success"
            style="width: 40px;height: 40px;color: #C5AA7B;"
          />
        </div>
      </div>
      <template #footer>
        <el-button class="leftBtn" @click="handleClose">取消</el-button>
        <el-button class="rightBtn" @click="toAfterSale">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { defineComponent, onBeforeMount, reactive, ref, shallowRef } from 'vue'
import { useRouter } from 'vue-router';

import OrderList from '@/components/base/orderList.vue'
import SvgIcon from '@/components/svgIcon/index.vue';
import {
  getOrderList,
  orderConfirm,
  orderCancel,
  orderDelete
} from '@/api/user/order.js'


defineComponent({
  name: 'MyOrder'
})

const router = useRouter();
/**
 * @type {object[]} orderList
 * @property {number} orderList[].status 订单状态 1-待付款 2-待发货 3-待收货 4-已完成 5-已取消
 */
let orderList = ref([]);
let listLoading = shallowRef(false);

let query = reactive({
  keyword: '',
  state: '',
});
let page = reactive({
  page: 1,
  pageSize: 5,
  total: 0,
});

function getTableList () {
  listLoading.value = true
  getOrderList({
    search: query.keyword,
    state: query.state,
    page: page.page,
    pageSize: page.pageSize
  }).then(response => {
    const res = response.data
    if (res.code === '200') {
      orderList.value = res.data.list
      page.total = parseInt(res.data.total)
      if (query.state === '4') {
        orderList.value = orderList.value.map(item => {
          if (item.ifNotComment === 1) {
            return item
          }
        }).filter(r => r);
      }
      orderList.value.forEach(item => {
        let flag = false
        item.skus.forEach(j => {
          if (j.ifAfter) {
            flag = true
          }
        })
        item.ifAfter = flag ? 1 : 0
      })
    }
  }).catch(err => {
    ElMessage.warning(err.message)
  }).finally(() => listLoading.value = false)
}
// 分页器跳转
function handleCurrentChange (val) {
  page.page = val
  getTableList()
}

/**
 * 订单类型
 */
let activeName = shallowRef('first');
// 订单类型切换
function handleClick (event) {
  if (event.index === '0') {
    query.state = ''
  } else if (event.index === '5') {
    query.state = 6
  } else {
    query.state = event.index
  }
  query.keyword = ''
  page.page = 1
  getTableList()
}

function searchOrder () {
  activeName.value = 'first'
  query.state = ''
  page.page = 1
  getTableList()
}

/**
 * 弹窗控制集合
 */
let visible = reactive({
  orderCancel: false,
  orderConfirm: false,
  orderDelete: false,
  orderRefund: false,
});
let orderId = shallowRef(null);
let checked = shallowRef(false); // 是否全选
let orderData = ref({});
let backList = ref([]); // 退货商品列表
let productIds = ref([]);

function handleOrderCancel () {
  if (!orderId.value) { return }
  orderCancel({
    orderId: orderId.value
  }).then(response => {
    const res = response.data
    if (res.code === '200') {
      ElMessage.success('订单取消成功')
      visible.orderCancel = false
      getTableList()
    }
  }).catch(err => ElMessage.error(err.message))
}

function handleOrderDelete () {
  if (!orderId.value) { return }
  orderDelete({
    orderId: orderId.value
  }).then(response => {
    const res = response.data
    if (res.code === '200') {
      ElMessage.success('订单删除成功')
      visible.orderDelete = false
      getTableList()
    }
  }).catch(err => ElMessage.error(err.message))
}

function handleOrderConfirm () {
  if (!orderId.value) { return }
  orderConfirm({
    orderId: orderId.value
  }).then(response => {
    const res = response.data
    if (res.code === '200') {
      ElMessage.success('确认收货成功')
      visible.orderConfirm = false
      getTableList()
    }
  }).catch(err => ElMessage.warning(err.message))
}

// 打开取消订单弹窗
function isCancel (id) {
  orderId.value = id
  visible.orderCancel = true
}
// 打开确认收货弹窗
function isConfirm (id) {
  orderId.value = id
  visible.orderConfirm = true
}
// 打开删除订单弹窗
function isDelete (id) {
  orderId.value = id
  visible.orderDelete = true
}

// 打开退货弹窗
function isRefund (data) {
  if (data.skus.length === 1) {
    router.push({
      path: '/afterSale',
      query: {
        orderData: JSON.stringify(data),
        state: 1
      }
    })
    return
  }
  let temp = []
  data.skus.forEach(i => {
    if (i.ifAfter) {
      temp.push(i)
    }
  })
  backList.value = temp // 全选判断
  orderData.value = data
  visible.orderRefund = true
}

// 关闭弹窗
function handleClose () {
  backList.value = []
  productIds.value = []
  checked.value = false
  visible.orderRefund = false
  visible.orderDelete = false
  visible.orderCancel = false
  visible.orderConfirm = false
}

// 选择退货商品
function select (item) {
  if (productIds.value.indexOf(item.skuId) === -1) {
    productIds.value.push(item.skuId)
  } else {
    productIds.value.splice(productIds.value.indexOf(item.skuId), 1)
  }
  checked.value = productIds.value.length === backList.value.length
}
function changeBox (val) {
  if (val) {
    productIds.value = []
    backList.value.forEach((item) => {
      productIds.value.push(item.skuId)
    })
  } else {
    productIds.value = []
  }
}
// 跳转到申请售后页面
function toAfterSale () {
  if (productIds.value.length === 0) {
    return ElMessage.warning('请先选择需要申请售后的商品')
  }
  var productData = []
  for (var k in productIds.value) {
    for (var i in orderData.value.skus) {
      if (orderData.value.skus[i].skuId === productIds.value[k]) {
        productData.push(orderData.value.skus[i])
      }
    }
  }
  var paramsData = JSON.parse(JSON.stringify(orderData.value))
  paramsData.skus = productData
  router.push({
    path: '/afterSale',
    query: {
      orderData: JSON.stringify(paramsData),
      state: 1
    }
  })
}

onBeforeMount(() => {
  getTableList()
})
</script>
<style lang="scss" scoped>
$navBarHeight: 50px;

.myOrder {
  width: 100%;
  font-size: 14px;
  box-sizing: border-box;
  position: relative;
  :deep(.el-tabs) {
    .el-tabs__header {
      background-color: #FAFAFA;
    }

    .el-tabs__nav {
      margin: 0 0 0 20px;
      height: $navBarHeight;
    }

    .el-tabs__item {
      height: $navBarHeight;
      line-height: $navBarHeight;
    }

    .el-tabs__nav-wrap::after {
      display: none;
    }
  }

  .search {
    width: 280px;
    height: $navBarHeight;
    font-size: 12px;
    margin-right: 20px;
    display: flex;
    align-items: center;
    position: absolute;
    top: 0;
    right: 0;

    .searchIcon {
      width: 24px;
      height: 24px;
      position: absolute;
      right: 8px;
      cursor: pointer;
    }

    :deep(.el-input) {
      // flex: 3;
      height: 40px;
      .el-input__wrapper{
        border-radius: 0;
      }
      .el-input-group__append {
        border-radius: 0;
        border-left: 0;

        .el-button {
          border-left: 0;
        }
      }
    }
  }

  :deep(.refund) {
    .el-dialog__body {
      display: flex;
      justify-content: center;
      background-color: #F8F8F8;
      padding: 20px 75px;
      box-sizing: border-box;

      .box {
        display: flex;
        flex-wrap: wrap;
        overflow-x: auto;
        height: 350px;
        width: 100%;
        text-align: center;
      }

      .el-checkbox {
        display: flex;
        align-items: center;
      }

      .el-checkbox__input {
        line-height: 18px;
      }

      .el-checkbox__label {
        font-size: 18px;
      }

      .back {
        width: 208px;
        padding: 10px 20px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        text-align: center;
        flex-direction: column;
        background-color: #FFFFFF;
        margin: 0 20px 20px 0;
        border: 1px solid transparent;
        position: relative;

        img {
          width: 171px;
          height: 171px;
        }

        .choice {
          width: 30px;
          height: 30px;
          position: absolute;
          bottom: 10px;
          right: 10px;
          display: none;
        }
      }

      .back:nth-of-type(3n) {
        margin-right: 0;
      }

      .backActive {
        border: 1px solid $mainGlod;

        .choice {
          display: block;
        }
      }
    }
  }
  :deep(.el-dialog__footer) {
    .leftBtn {
      background-color: #F3F4F5;
      color: #333;
      border-radius: 0;
    }

    .rightBtn {
      color: $mainGlod;
      background-color: #333;
      box-sizing: border-box;
      border-radius: 0;
    }
  }
}

.sub-main {
  min-height: 400px;
}
</style>
